import * as echarts from 'echarts';

// 指标配置
export const metricsConfig = {
    wellDepth: { name: '井深', color: '#3b82f6', key: 'wellDepth' },
    torque: { name: '顶驱扭矩', color: '#8b5cf6', key: 'torque' },
    rpm: { name: '顶驱转速', color: '#ec4899', key: 'rpm' },
    pressure: { name: '立管压力', color: '#f59e0b', key: 'pressure' },
    flow: { name: '入口流量', color: '#10b981', key: 'flow' },
    rop: { name: '钻时', color: '#06b6d4', key: 'rop' },
    wob: { name: '钻压', color: '#ef4444', key: 'wob' }
};

// 数据存储
export const dataStore = {
    wellDepth: [],
    torque: [],
    rpm: [],
    pressure: [],
    flow: [],
    rop: [],
    wob: []
};

// 配置项
export const MAX_DATA_POINTS = 50;

/**
 * 创建图表配置
 */
function createChartOption(metricKey) {
    const config = metricsConfig[metricKey];
    return {
        grid: {
            left: '12%',
            right: '8%',
            top: '8%',
            bottom: '12%'
        },
        xAxis: {
            type: 'value',
            splitLine: {
                lineStyle: {
                    color: '#2d3748',
                    type: 'dashed'
                }
            },
            axisLabel: {
                color: '#94a3b8',
                fontSize: 10
            },
            axisLine: {
                lineStyle: {
                    color: '#475569'
                }
            }
        },
        yAxis: {
            type: 'time',
            splitLine: {
                lineStyle: {
                    color: '#2d3748',
                    type: 'dashed'
                }
            },
            axisLabel: {
                color: '#94a3b8',
                fontSize: 10,
                formatter: function(value) {
                    const date = new Date(value);
                    return date.getHours().toString().padStart(2, '0') + ':' +
                           date.getMinutes().toString().padStart(2, '0') + ':' +
                           date.getSeconds().toString().padStart(2, '0');
                }
            },
            axisLine: {
                lineStyle: {
                    color: '#475569'
                }
            }
        },
        series: [{
            type: 'line',
            data: [],
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            lineStyle: {
                color: config.color,
                width: 2
            },
            itemStyle: {
                color: config.color
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0,
                        color: config.color + '80'
                    }, {
                        offset: 1,
                        color: config.color + '10'
                    }]
                }
            }
        }],
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: config.color,
            textStyle: {
                color: '#fff',
                fontSize: 11
            },
            formatter: function(params) {
                if (params.length > 0) {
                    const date = new Date(params[0].value[1]);
                    const timeStr = date.toLocaleTimeString('zh-CN');
                    return `${config.name}: <b>${params[0].value[0].toFixed(2)}</b><br/>时间: ${timeStr}`;
                }
                return '';
            }
        }
    };
}

/**
 * 初始化所有图表
 */
export function initCharts() {
    const charts = {};
    Object.keys(metricsConfig).forEach(key => {
        const chartDom = document.getElementById(`chart${key.charAt(0).toUpperCase() + key.slice(1)}`);
        if (chartDom) {
            charts[key] = echarts.init(chartDom);
            charts[key].setOption(createChartOption(key));
        }
    });
    return charts;
}

/**
 * 更新图表数据
 */
export function updateChart(charts, metricKey, value, timestamp) {
    const data = dataStore[metricKey];
    
    // 添加新数据点 [值, 时间] - X轴是指标值，Y轴是时间
    data.push([value, timestamp]);
    
    // 保持数据点数量不超过MAX_DATA_POINTS
    if (data.length > MAX_DATA_POINTS) {
        data.shift();
    }

    // 更新图表
    if (charts[metricKey]) {
        charts[metricKey].setOption({
            series: [{
                data: data
            }]
        });
    }
}

/**
 * 更新底部最新值
 */
export function updateMetricValue(metricKey, value) {
    const elementId = `value${metricKey.charAt(0).toUpperCase() + metricKey.slice(1)}`;
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = value.toFixed(2);
    }
}

/**
 * 调整所有图表大小
 */
export function resizeCharts(charts) {
    Object.values(charts).forEach(chart => {
        if (chart) {
            chart.resize();
        }
    });
}